package com.jesse.custom.component;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

import com.jesse.custom.component.SuperButton;
import com.jesse.main.R;
import com.jesse.util.ViewUtil;

/**
 * 自动倒计时按钮
 * @author jesse_000
 *
 */
public class TimerButton extends LinearLayout{

	private static SuperButton timeButton;
	private static Timer timer;
	private static TimerTask timerTask;
	private OnClickListener onClickListener;
	//当前剩余时间
	private static Map<String, Integer> remainingTimeMap = new HashMap<String, Integer>();
	//原定时间
	private static Map<String, Integer> totalTimeMap = new HashMap<String, Integer>();
	//当前按钮的唯一标示（使用按钮所在类名区别，一般情况一个页面只有一个倒计时按钮）
	private String currentButtonKey;
	
	private String buttonString;
	
	private final int LOCK_BUTTON = 1;
	private final int UNLOCK_BUTTON = 2;
	private int normalBgColor = 0;
	private int focusBgColor = 0;
	
	public TimerButton(Context context) {
		this(context, null);
	}

	public TimerButton(Context context, AttributeSet attrs) {
		super(context, attrs);
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.unit_time_button, this);
		timeButton = (SuperButton) findViewById(R.id.timeButton);
		normalBgColor = R.color.green_light;
		focusBgColor = R.color.green;
		timeButton.initButton(getContext().getString(R.string.obtain_smsCode), R.color.white, normalBgColor, focusBgColor);
	}
	
	/**
	 * 初始化倒计时按钮
	 * @param context
	 * @param buttonText	未开始倒计时时显示的文字
	 * @param timeLength	倒计时周期
	 * @param listener		点击监听事件
	 */
	public void initTimeButton(Context context, String buttonText, int timeLength) {
		initTimeButton(context, context.getClass().getName(), buttonText, timeLength);
	}
	
	public void initTimeButton(Context context, String key, String buttonText, int timeLength) {
		currentButtonKey = context.getClass().getName();
		totalTimeMap.put(currentButtonKey, timeLength);
		buttonString = buttonText;
		
		startTimer();
		checkTime();
	}
	
	public void initTimeButtonColor(int normalBgColor, int focusBgColor) {
		this.normalBgColor = normalBgColor;
		this.focusBgColor = focusBgColor;
		timeButton.initButton(buttonString, R.color.white, normalBgColor, focusBgColor);
	}
	
	/**
	 * 启动倒计时
	 */
	private void startTimer() {
		if (timer != null) return;
		if (remainingTimeMap.isEmpty()) return;
		timer = new Timer();
		timerTask = new TimerTask() {
			
			@Override
			public void run() {
				countDownRun();
			}
		};
		timer.schedule(timerTask, 1000, 1000);
	}
	
	private void countDownRun() {
		if (subTime() == 0) {
			if (remainingTimeMap.isEmpty()) {
				reset();
			}
			Message.obtain(handler, UNLOCK_BUTTON).sendToTarget();
			return;
		}
		Message.obtain(handler, LOCK_BUTTON).sendToTarget();
		
	}
	
	private int subTime() {
		if (remainingTimeMap.isEmpty()) {
			return 0;
		}
		
		Iterator<String> iterator = remainingTimeMap.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
		    int time = remainingTimeMap.get(key);
		    remainingTimeMap.put(key, --time);
		}
		
		int currentTime = remainingTimeMap.get(currentButtonKey);
		if (currentTime <= 0) {
			remainingTimeMap.remove(currentButtonKey);
		}  else {
			ViewUtil.Debug("倒计时" + currentTime);
		}
		return currentTime;
	}
	
	private void checkTime() {
		if (remainingTimeMap.get(currentButtonKey) != null && remainingTimeMap.get(currentButtonKey) > 0) {
			lockButton();
		}
	}
	
	public void startSub() {
		if (!timeButton.isTouchEnable()) return;
		
		remainingTimeMap.put(currentButtonKey, totalTimeMap.get(currentButtonKey));
		countDownRun();
		startTimer();
	}
	
	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		public void handleMessage(Message message){
			switch (message.what) {
			case LOCK_BUTTON:
				lockButton();
				break;
			case UNLOCK_BUTTON:
				unLockButton();
				break;
			}
		}
	};
	
	private void lockButton() {
		if (timeButton != null) {
			timeButton.setButtonBackgroundColor(getContext().getResources().getColor(R.color.btn_gray));
			timeButton.setTouchEnable(false);
			timeButton.setButtonText(remainingTimeMap.get(currentButtonKey) + "");
		}
	}
	
	private void unLockButton() {
		if (timeButton != null) {
			timeButton.initButton(buttonString, R.color.white, normalBgColor, focusBgColor);
			timeButton.setTouchEnable(true);
		}
	}
	
	private void reset() {
        if (timerTask != null && timer != null) {
        	timerTask.cancel();
        	timer.cancel();
        	timerTask = null;
        	timer = null;
        }
	}
	
	@Override
	public void setOnClickListener(OnClickListener l) {
		super.setOnClickListener(l);
		onClickListener = l;
		timeButton.setOnClickListener(timeClickListener);
	}
	
	private OnClickListener timeClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			onClickListener.onClick(TimerButton.this);
		}
	};
}
